'use strict';

import { wineModel } from "../model/wine";
import { ServiceBase, Exceptions } from '../kalend';
import { customer_accountService } from "./customer_account";
import _ = require("underscore");
import { common } from "../middleware/common";
var moment = require('moment');

class WineService extends ServiceBase {
    constructor() {
        super(wineModel)
    }
    async query(params: any) {
        const offset = params.offset;
        const limit = params.limit;
        const uid = params.uid;
        const mid = params.mid;
        const starttime = params.starttime;
        const endtime = params.endtime;
        const source = params.source;

        let filter: any = {};
        if (uid) {
            filter.userid = uid;
        }
        if (mid) {
            filter.merchantid = mid;
        }
        if (source && source != 'all') {
            filter.source = source;
        }
        if (starttime) {
            filter.updateTime = { '$gte': new Date(moment(new Date(starttime)).format('YYYY-MM-DD') + '  00:00:00') };
        }
        if (endtime) {
            if (filter.updateTime) {
                filter.updateTime['$lte'] = new Date(moment(endtime).format('YYYY-MM-DD') + '  23:59:59');
            } else {
                filter.updateTime = { '$lte': new Date(moment(endtime).format('YYYY-MM-DD') + '  23:59:59') };
            }
        }
        let data: any = await this.queryPagination(offset, limit, {
            filter: filter,
            populateOptions: [{
                path: 'userid',
                select: 'nickname'
            }, {
                path: 'merchantid',
                select: 'name'
            }, {
                path: 'orderid',
                select: 'code'
            }]
        });
        // let addI = data.rows.filter((a: any) => {
        //     return a.source !== 1 && a.conins > 0;
        // });
        // let jI = data.rows.filter((a: any) => {
        //     return a.source === 1 && a.conins > 0;
        // });

        // let addITotal = eval(_.pluck(addI, 'conins').join('+')) || 0;
        // let jITotal = eval(_.pluck(jI, 'conins').join('+')) || 0;
        // let ch = addITotal - jITotal;
        // if (ch >= 0) {
        //     data.footTotal = `共计酒币 +${ch} 个 `;
        // } else {
        //     data.footTotal = `共计酒币 -${ch} 个 `;
        // }

        let addITotal = 0;
        let jITotal = 0;
        data.rows = data.rows.map((item: any) => {
            item.nickname = item.userid ? item.userid.nickname : '';
            item.mername = item.merchantid ? item.merchantid.name : '';
            item.ordercode = item.orderid ? item.orderid.code : '';
            switch (item.source) {
                case 1:
                    item.source = '买单消费';
                    break;
                case 2:
                    item.source = '升级黄金会员';
                    break;
                case 3:
                    item.source = '邀请奖励';
                    break;
                case 4:
                    item.source = '活动奖励';
                    break;
                case 5:
                    item.source = '后台更新';
                    break;
                case 6:
                    item.source = '升级白金会员';
                    break;
                    case 7:
                    item.source = '升级钻石会员';
                    break;
                default:
                    break;
            }
            if (item.source == 1) {
                jITotal = common.add(jITotal, item.conins);
            } else {
                addITotal = common.add(addITotal, item.conins);
            }
            return item;
        });
        data.footTotal = `共计酒币 ${addITotal - jITotal} 个 `;

        return data;
    }
    /** 生成酒币消费记录 */
    async consuwin(orderdata: any, type: any, source: Number) {
        let conins = orderdata.conins;
        let uid = orderdata.customerid;
        let openid = orderdata.openid;
        let filter: any = {
            status: 1
        };

        if (openid) {
            filter.openid = openid;
        }
        if (uid) {
            filter._id = uid;
        }
        const userdata = await customer_accountService.querySingle(filter, { select: 'coinbalance' });
        let doc: any = {
            openid: openid,
            conins: conins,
            orderid: orderdata._id,
            source: source
        };
        if (userdata) {
            doc.userid = userdata._id;
            doc.originwine = userdata.coinbalance;
        } else {
            doc.originwine = 0;
            doc.isaddnew = true;
            doc.remark = '订单支付成功未找到用户信息新增';
        }
        if (type === 'add') {
            doc.coinbalance = Number(doc.originwine) + Number(conins);
        } else {
            doc.coinbalance = Number(doc.originwine) - Number(conins);
        }
        this.create(doc);
    }
    async getWines(userid: any) {
        let result = 0;
        let data = await wineModel.aggregate([
            {
                $match: {
                    source: 1,
                    userid: userid
                }
            },
            {
                $group: { _id: "$userid", total: { $sum: '$conins' } },

            }
        ]);
        if (data && data.length > 0) {
            result = data[0].total;
        }
        return result;
    }
}

export const wineService = new WineService();